//
//  Group.m
//  Group Context
//
//  Created by Chris Karr on 2/13/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "Group.h"
#import "ApplicationDelegate.h"

#define UPDATE_INTERVAL 300
#define USER @"Username"
#define PASS @"Password"
#define URL @"URL"

@implementation Group

- (Group *) init
{
	if (self = [super init])
	{
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:UPDATE_STATUS object:nil];
		users = [[NSMutableArray alloc] init];
	}

	formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeStyle:NSDateFormatterShortStyle];
	
	return self;
}

- (void) updateTimer:(NSTimer *) theTimer
{
	[[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_STATUS object:self];
}

- (void) update:(NSNotification *) notification
{
	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	NSString * user = [defaults stringForKey:USER];
	NSString * pass = [defaults stringForKey:PASS];
	NSString * url = [defaults stringForKey:URL];

	if (user == nil || url == nil || pass == nil)
	{
		[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_UPDATE object:self
			userInfo:[NSDictionary dictionaryWithObject:@"Please set your preferences." forKey:STATUS]];

		[[NSApp delegate] preferences:self];

		return;
	}

	[users removeAllObjects];

	NSString * urlString = [NSString stringWithFormat:@"http://%@:%@@%@", user, pass, url];
	
	NSXMLDocument * xml = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL URLWithString:urlString] options:0 error:nil];
	
	if (xml != nil)
	{
		[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_UPDATE object:self 
			userInfo:[NSDictionary dictionaryWithObject:@"Downloading status..." forKey:STATUS]];

		NSXMLElement * root = [xml rootElement];
		
		NSMutableDictionary * groupDict = [NSMutableDictionary dictionary];
		
		for (NSXMLElement * user in [root elementsForName:@"user"])
		{
			NSMutableDictionary * dict = [groupDict valueForKey:[[user attributeForName:@"name"] stringValue]];
			
			if (dict == nil)
			{
				dict = [NSMutableDictionary dictionary];
					[groupDict setValue:dict forKey:[[user attributeForName:@"name"] stringValue]];
			}

			NSDate * update = [NSDate dateWithNaturalLanguageString:[[user attributeForName:@"date"] stringValue]];
			[dict setValue:update forKey:@"date"];

			[dict setValue:[[user attributeForName:@"name"] stringValue] forKey:@"name"];
			[dict setValue:[[user attributeForName:@"icon"] stringValue] forKey:@"icon"];
			[dict setValue:[[user attributeForName:@"value"] stringValue] forKey:[[user attributeForName:@"field"] stringValue]];
		}
		
		[users addObjectsFromArray:[groupDict allValues]];
		
		[[NSNotificationCenter defaultCenter] postNotificationName:TABLE_UPDATE object:self 
			userInfo:[NSDictionary dictionaryWithObject:[[root attributeForName:@"name"] stringValue] forKey:TITLE]];
			
		[xml release];

		NSDate * nextUpdate = [NSDate dateWithTimeIntervalSinceNow:UPDATE_INTERVAL];

		NSString * status = [NSString stringWithFormat:@"Next update: %@", [formatter stringFromDate:nextUpdate]];

		[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_UPDATE object:self 
			userInfo:[NSDictionary dictionaryWithObject:status forKey:STATUS]];
	}
	else
	{
		[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_UPDATE object:self 
			userInfo:[NSDictionary dictionaryWithObject:@"Error downloading status." forKey:STATUS]];
	}
	
	[NSTimer scheduledTimerWithTimeInterval:UPDATE_INTERVAL target:self selector:@selector(updateTimer:) userInfo:nil repeats:NO];
}

- (NSInteger) numberOfRowsInTableView:(NSTableView *) aTableView
{
	return [users count];
}

- (id) tableView:(NSTableView *) aTableView objectValueForTableColumn:(NSTableColumn *) aTableColumn row:(NSInteger) rowIndex
{
	if ([[aTableColumn identifier] isEqual:@"icon"])
	{
		NSString * imagePath = [[users objectAtIndex:rowIndex] valueForKey:@"icon"];
	
		if (imagePath != nil)
			return [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:imagePath]];
		else
			return nil;
	}
	else
	{
		NSDictionary * user = [users objectAtIndex:rowIndex];
		
		[[NSNotificationCenter defaultCenter] postNotificationName:CONTEXT_REPORT object:self userInfo:user];
		
		NSDictionary * atts = nil;
		
		NSMutableString * htmlString = [NSMutableString stringWithFormat:@"<span style='font-family: Lucida Grande; font-size: 8pt'>\
																<b style='font-size: 10pt'>%@</b><br />", [user valueForKey:@"name"]];
		
		for (NSString * key in [user allKeys])
		{
			if (!([key isEqual:@"name"] || [key isEqual:@"date"] || [key isEqual:@"icon"]))
				[htmlString appendString:[NSString stringWithFormat:@"%@: %@<br />", key, [user valueForKey:key]]];
		}

		[htmlString appendString:[NSString stringWithFormat:@"Last update: %@<br />", [formatter stringFromDate:[user valueForKey:@"date"]]]];
		
		[htmlString appendString:@"</span>"];
		
		return [[NSAttributedString alloc] initWithHTML:[htmlString dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:&atts];
	}
}

@end
